<?php

namespace App\Http\Controllers\api;

use App\Http\Controllers\Controller;
use App\Models\product\ProductSonModel;
use App\Models\users\UsersModel;
use App\Models\users\UsersNewModel;
use App\Models\users\UsersNewProductRecordModel;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use lxs\api\ApiResponse;

class AuthorizationController extends Controller
{
    /**
     * APi分销注册
     */
    public function apiRegister(): JsonResponse
    {
        $data = request()->data;

        $validator = Validator::make($data, [
            'unique' => ['required', function ($attribute, $value, $fail) {
                $topUser = UsersModel::where('unique_id', $value)->first();
                if (!$topUser) {
                    $fail('邀请码不正确');
                }
            }],
            'mobile' => ['required', 'regex:/^1[34578]\d{9}$/', function ($attribute, $value, $fail) {
                $user_list = UsersModel::where('mobile', $value)->first();
                if ($user_list) {
                    $fail('该手机号码已注册');
                }
            }],
            'pro' => ['required', function ($attribute, $value, $fail) {
                $product = ProductSonModel::where('id', $value)->first();
                if (!$product) {
                    $fail('商品不存在');
                }
            }]
        ], [
            'unique.required' => '请填写邀请码',
            'mobile.required' => '请填写手机号码',
            'mobile.regex' => '手机号码格式不正确',
            'pro.required' => '请选择商品',
        ]);

        if ($validator->fails()) {
            return ApiResponse::apiResponseData(400, $validator->errors()->first());
        }

        try {
            DB::beginTransaction();

            $topUser = UsersModel::where('unique_id', $data['unique'])->first();
            if (!$topUser) {
                return ApiResponse::apiResponseData(404, '邀请码不正确');
            }

            $newInfo = UsersNewModel::where('mobile', $data['mobile'])->first();
            if ($newInfo) {
                return ApiResponse::apiResponseData(404, '该手机号码已注册');
            } else {
                $newInfo = new UsersNewModel();
                $newInfo->uid = $topUser->id;
                $newInfo->mobile = $data['mobile'];
                $newInfo->nickname = $data['nickname'] ?? '';
                $newInfo->avatar = $data['avatar'] ?? '';
                $newInfo->create_time = time();
                $newInfo->save();
            }


            if (isset($data['pro'])) {
                $newProduct = UsersNewProductRecordModel::where('product_id', $data['pro'])
                    ->where('new_id', $newInfo->id)
                    ->where('uid', $topUser->id)
                    ->first();
                if ($newProduct) {
                    return ApiResponse::apiResponseData(404, '该商品已有该拉新用户');
                }
                $laxin = new UsersNewProductRecordModel();
                $laxin->product_id = $data['pro'];
                $laxin->new_id = $newInfo->id;
                $laxin->uid = $topUser->id;
                $laxin->create_time = time();
                $laxin->save();
            }

            DB::commit();
            return ApiResponse::apiResponseData(200, '拉新成功');

        } catch (\Exception $e) {
            DB::rollBack();
            Log::error(date('Y-m-d H:i:s') . '分销拉新: ' . $e->getMessage() . $e->getLine() . $e->getFile());
            return ApiResponse::apiResponseData(404, '拉新失败');
        }
    }

}
